import React, { Component } from 'react';

export default class LazyRoute extends Component {
    constructor(props) {
        super(props);
        this.state = {
            component: null
        }
    }

    componentDidMount() {
        this.loadComponent(this.props.component);
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.component && nextProps.component !== prevState.component) {
            return nextProps.component.then(module => {
                return {
                    component: module.default
                }
            })
        } else {
            return null;
        }
    }
    
    loadComponent(componentPromise) {
        componentPromise.then(module => {
            this.setState({
                component: module.default
            })
        })
    }
  
    render() {
        const C = this.state.component;
        return C ? <C {...this.props}/> : null
    }
}